package KylinComponents

import (
	"encoding/json"

	"fmt"
	"regexp"
	"runtime"
	"strings"
)

func JsonMar(data interface{}) []byte {
	d, err := json.Marshal(data)
	if err != nil {
		LogError(nil, fmt.Sprintf("%s", err))
	}
	return d
}
func JsonUnMar(data []byte) interface{} {
	var d interface{}
	err := json.Unmarshal(data, &d)
	if err != nil {
		LogError(nil, fmt.Sprintf("%s", err))
	}
	return d
}

func RunFuncName() string {
	pc := make([]uintptr, 1)
	runtime.Callers(2, pc)
	f := runtime.FuncForPC(pc[0])
	return f.Name()
}

func Condition(condition bool, trueVal string, falseVal string) string {
	if condition {
		return trueVal
	}
	return falseVal
}

func ToUrl(host string, str ...string) string {
	result := host
	for _, v := range str {
		if strings.Contains(v, "?") {
			result = result + v
		} else {
			if result[len(result)-1:] == "/" {
				result = result + v
			} else {
				result = result + "/" + v
			}
		}
	}
	return result
}

func Interface2String(inter interface{}) string {
	switch inter.(type) {
	case string:
		return fmt.Sprintf("%s", inter)
	case int:
		return fmt.Sprintf("%d", inter)
	case float64:
		return fmt.Sprintf("%f", inter)
	default:
		return ""
	}
}
func PathCut(str string, index int) string {
	reg := regexp.MustCompile(`/$`)
	str2 := reg.ReplaceAllString(str, "") //替换掉最末尾多余 /
	str3 := strings.Split(str2, "/")      //使用/进行分割字符串
	length := len(str3) - 1
	if index == -1 { //默认移除最后路径
		index = length
	} else { //移除指定位置路径
		if index > length {
			index = length
		}
	}
	return strings.Join(append(str3[:index], str3[index+1:]...), "/")
}
